from flask import jsonify, request
from flask.views import MethodView
from app.models.article import Article
from webargs import fields
from webargs.flaskparser import parser


parser_args = {
    'page': fields.Int(missing=0, error_messages={'invalid': '必须是数值类型'}),
    'cid': fields.Int(),
}


class ArticleAPI(MethodView):
    def get(self, id):
        model = Article.query.get_or_404(id)
        return jsonify(success=True, data=model.to_dict(content=True))


class ArticlesAPI(MethodView):
    def get(self):
        args = parser.parse(parser_args, request)
        query = Article.query.filter(Article.status==9).order_by(Article.id.desc())
        query = query.filter(Article.cid==args.get('cid')) if args.get('cid') else query
        data = Article.to_collection_dict(query, args['page'], 10)
        return jsonify(success=True, data=data)
